package com.ip.user.api;

import com.ip.user.models.common.annotation.RequiresPermission;
import com.ip.user.config.JwtTokenUtil;
import com.ip.user.models.bo.UserBO;
import com.ip.user.models.service.UserService;
import com.ip.user.models.vo.UserVO;
import com.ip.user.util.TokenUtil;
import com.ip.common.constant.PageResult;
import com.ip.common.constant.Result;
import com.ip.common.enums.CodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("api/users")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    
    @Autowired
    private UserDetailsService userDetailsService;
    
    @Autowired
    private TokenUtil tokenUtil;
    
    /**
     * 创建用户
     */
    @PostMapping("/create")
    @RequiresPermission("sys:user:add")
    public Result<UserVO> createUser(@RequestBody UserBO userBO) {
        try {
            UserVO user = userService.createUser(userBO);
            Result<UserVO> result = new Result<>();
            result.setCode(CodeEnum.SUCCESS.getCode());
            result.setMsg(CodeEnum.SUCCESS.getMsg());
            result.setData(user);
            return result;
        } catch (Exception e) {
            Result<UserVO> result = new Result<>();
            result.setCode(CodeEnum.FAIL_100001.getCode());
            result.setMsg(e.getMessage());
            result.setData(null); // 添加这行以确保设置了data字段
            return result;
        }
    }

    /**
     * 获取所有用户 (支持分页查询)
     */
    @GetMapping( "/list")
    @RequiresPermission("sys:user:list")
    public PageResult<List<UserVO>> getAllUsers(
        @RequestParam(defaultValue = "1") int pageNo,
        @RequestParam(defaultValue = "10") int pageSize,
        @RequestParam(defaultValue = "") String username,
        @RequestParam(required = false) Integer status
    ) {
        try {
            // 使用分页查询
            List<UserVO> users = userService.getUsersByPage(pageNo, pageSize, username, status);
            int totalCount = userService.getUserCount(username, status);
            
            // 创建带有分页信息的结果对象
            PageResult<List<UserVO>> result = new PageResult<>();
            result.setCode(CodeEnum.SUCCESS.getCode());
            result.setMsg(CodeEnum.SUCCESS.getMsg());
            result.setData(users);
            
            // 添加分页信息
            int totalPages = (int) Math.ceil((double) totalCount / pageSize);
            result.setTotal(totalCount);
            result.setPageNo(pageNo);
            result.setPageSize(pageSize);
            result.setTotalPages(totalPages);
            
            return result;
        } catch (Exception e) {
            PageResult<List<UserVO>> result = new PageResult<>();
            result.setCode(CodeEnum.FAIL_100001.getCode());
            result.setMsg(e.getMessage());
            result.setData(null); // 添加这行以确保设置了data字段
            return result;
        }
    }
    
    /**
     * 更新用户信息
     */
    @PutMapping("/update")
    public Result<UserVO> updateUser(@RequestBody UserBO userBO) {
        try {
            UserVO user = userService.updateUser(userBO);
            Result<UserVO> result = new Result<>();
            result.setCode(CodeEnum.SUCCESS.getCode());
            result.setMsg(CodeEnum.SUCCESS.getMsg());
            result.setData(user);
            return result;
        } catch (Exception e) {
            Result<UserVO> result = new Result<>();
            result.setCode(CodeEnum.FAIL_100001.getCode());
            result.setMsg(e.getMessage());
            result.setData(null); // 添加这行以确保设置了data字段
            return result;
        }
    }
    
    /**
     * 删除用户
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteUser(@PathVariable Long id) {
        try {
            userService.deleteUser(id);
            Result<Void> result = new Result<>();
            result.setCode(CodeEnum.SUCCESS.getCode());
            result.setMsg(CodeEnum.SUCCESS.getMsg());
            result.setData(null); // 添加这行以确保设置了data字段
            return result;
        } catch (Exception e) {
            Result<Void> result = new Result<>();
            result.setCode(CodeEnum.FAIL_100001.getCode());
            result.setMsg(e.getMessage());
            result.setData(null); // 添加这行以确保设置了data字段
            return result;
        }
    }
    
    /**
     * 切换用户状态
     */
    @PostMapping("/toggle-status")
    @RequiresPermission("sys:user:toggle")
    public Result<Void> toggleUserStatus(@RequestParam Long userId, @RequestParam Integer status) {
        try {
            // 调用服务更新用户状态
            userService.updateUserStatus(userId, status);
            
            Result<Void> result = new Result<>();
            result.setCode(CodeEnum.SUCCESS.getCode());
            result.setMsg("用户状态更新成功");
            result.setData(null); // 添加这行以确保设置了data字段
            return result;
        } catch (Exception e) {
            Result<Void> result = new Result<>();
            result.setCode(CodeEnum.FAIL_100001.getCode());
            result.setMsg("用户状态更新失败: " + e.getMessage());
            result.setData(null); // 添加这行以确保设置了data字段
            return result;
        }
    }
    
    /**
     * 刷新JWT Token
     */
    @PostMapping("/refresh-token")
    public ResponseEntity<?> refreshToken(@RequestHeader("Authorization") String authorizationHeader) {
        try {
            if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
                String oldToken = authorizationHeader.substring(7);
                
                // 从旧Token中获取用户名
                String username = jwtTokenUtil.getUsernameFromToken(oldToken);
                
                // 加载用户详情
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                
                // 生成新Token
                String newToken = jwtTokenUtil.generateToken(userDetails);
                
                // 保存新Token到Redis（用于单设备登录控制）
                tokenUtil.saveUserToken(username, newToken);
                
                // 返回新Token
                Map<String, String> response = new HashMap<>();
                response.put("token", newToken);
                return ResponseEntity.ok(response);
            } else {
                return ResponseEntity.badRequest().body("Invalid token format");
            }
        } catch (Exception e) {
            return ResponseEntity.status(500).body("Error refreshing token: " + e.getMessage());
        }
    }
}